﻿using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsApp1.entity;

namespace WinFormsApp1.utils
{
    public class DbUtils
    {

        private static Setting setting;
        public static Setting Setting { get { return setting; } }


        private static SQLiteConnection connection;
        private static string dbPath;
        public static void DbInit()
        {
            dbPath = Application.ExecutablePath;
            dbPath = dbPath.Substring(0, dbPath.LastIndexOf("\\"));
            dbPath += "\\CountdownDb.db";

            int executeCount = -1;

            if (! File.Exists(dbPath))
            {
                File.Create(dbPath).Close();
            }
            connection = new SQLiteConnection(dbPath);
            connection.CreateTable<Setting>();
            List<Setting> settingList = connection.Query<Setting>("SELECT * FROM setting;");

            if (settingList?.Count > 0)
            {
                setting = settingList[0];
            }
            else
            {
                //MessageBox.Show("数据库连接错误！请联系开发者解决！", "救命，有BUG！");
                //Environment.Exit(0);
                setting = new Setting();
                SaveSetting(setting);
            }
         }

        public static void SaveSetting(Setting setting)
        {
            if (setting != null)
            {
                connection?.DeleteAll<Setting>();
                int? v = connection?.Insert(setting);
                if (v != null)
                {
                    DbUtils.setting = setting;
                }
                else
                {
                    MessageBox.Show("保存数据错误！");
                }
            }
            
        }
    }
}
